package com.sl.transport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sl.transport.common.exception.SLException;
import com.sl.transport.domain.OrganDTO;
import com.sl.transport.enums.ExceptionEnum;
import com.sl.transport.repository.OrganRepository;
import com.sl.transport.service.OrganService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 机构的service
 */

@Service
public class OrganServiceImpl implements OrganService {


    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private OrganRepository organRepository;

    /**
     * 无需指定type，根据id查询
     *
     * @param bid 机构id
     * @return
     */
    @Override
    public OrganDTO findByBid(Long bid) {
        return organRepository.findByBid(bid);
    }

    /**
     * 无需指定type，根据ids查询
     *
     * @param bids 机构ids
     * @return
     */
    @Override
    public List<OrganDTO> findByBids(List<Long> bids) {
        return organRepository.findByBids(bids);
    }

    /**
     * 询所有的机构，如果name不为空的按照name模糊查询
     *
     * @param name 机构名称
     * @return
     */
    @Override
    public List<OrganDTO> findAll(String name) {
        return organRepository.findAll(name);
    }

    /**
     * 查询机构树
     *
     * @return
     */
    @Override
    public String findAllTree() {
        List<OrganDTO> nodeList = findAll(null);

        List<Tree<Long>> build = TreeUtil.build(nodeList, 0L, ((organDTO, tree) -> {
            tree.setId(organDTO.getId());
            tree.setParentId(organDTO.getParentId());

            // 这里面也包含有parentId,上面虽然也写了但是不冲突,能让你知道需要设置parentId
            tree.putAll(BeanUtil.beanToMap(organDTO));
            // 这个可能就是防止信息泄露
            // tree.remove("bid");
        }));

        // 转为JSON字符串
        try {
            return this.objectMapper.writeValueAsString(build);
        } catch (JsonProcessingException e) {
            throw new SLException(ExceptionEnum.ORGAN_TREE_ERROR);
        }
    }

}
